package com.lyy.system.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyy.common.utils.*;
import com.lyy.common.utils.excel.ExcelUtils;
import com.lyy.common.utils.jxls.JxlsExport;
import com.lyy.system.pojo.SysVcodeLog;
import com.lyy.system.service.SysVcodeLogService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 发送消息记录(SysVcodeLog)表控制层
 *
 * @author Yw
 * @since 2021-02-02 17:48:43
 */
@RestController
@RequestMapping("/sysVcodeLog")
public class SysVcodeLogController {
    /**
     * 服务对象
     */
    @Resource
    private SysVcodeLogService sysVcodeLogService;

    /**
     * 创建发送消息记录
     * /sysVcodeLog/createSysVcodeLog
     * { "username":"手机号码",  "vcode":"动态密码",  "createDate":"获取时间" }
     *
     * @param username   手机号码
     * @param vcode      动态密码
     * @param createDate 获取时间
     * @return
     */
    @PostMapping("/createSysVcodeLog")
    public Map<String, Object> createSysVcodeLog(SysVcodeLog sysVcodeLog) {
        AssertUtils.notNull(sysVcodeLog.getUsername(), "手机号码不能为空");
        AssertUtils.notNull(sysVcodeLog.getVcode(), "动态密码不能为空");
        AssertUtils.notNull(sysVcodeLog.getCreateDate(), "获取时间不能为空");
        sysVcodeLogService.createSysVcodeLog(sysVcodeLog);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 根据主键修改发送消息记录
     * /sysVcodeLog/updateSysVcodeLog
     * { "id":"消息记录",  "username":"手机号码",  "vcode":"动态密码",  "createDate":"获取时间" }
     *
     * @param id         消息记录
     * @param username   手机号码
     * @param vcode      动态密码
     * @param createDate 获取时间
     * @return
     */
    @PutMapping("/updateSysVcodeLog")
    public Map<String, Object> updateSysVcodeLog(SysVcodeLog sysVcodeLog) {
        AssertUtils.notNull(sysVcodeLog.getId(), "消息记录不能为空");
        AssertUtils.notNull(sysVcodeLog.getUsername(), "手机号码不能为空");
        AssertUtils.notNull(sysVcodeLog.getVcode(), "动态密码不能为空");
        AssertUtils.notNull(sysVcodeLog.getCreateDate(), "获取时间不能为空");
        sysVcodeLogService.updateSysVcodeLog(sysVcodeLog);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 根据主键获取单个发送消息记录
     * /sysVcodeLog/getSysVcodeLog
     * { "id":"消息记录" }
     *
     * @param id 消息记录
     * @return
     */
    @GetMapping("/getSysVcodeLog")
    public Map<String, Object> getSysVcodeLog(SysVcodeLog sysVcodeLog) {
        AssertUtils.notNull(sysVcodeLog.getId(), "消息记录不能为空");
        SysVcodeLog entity = sysVcodeLogService.getSysVcodeLog(sysVcodeLog);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sysVcodeLog", entity);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 根据主键删除发送消息记录
     * /sysVcodeLog/deleteSysVcodeLog
     * { "id":"消息记录" }
     *
     * @param id 消息记录
     * @return
     */
    @DeleteMapping("/deleteSysVcodeLog")
    public Map<String, Object> deleteSysVcodeLog(SysVcodeLog sysVcodeLog) {
        AssertUtils.notNull(sysVcodeLog.getId(), "消息记录不能为空");
        sysVcodeLogService.deleteSysVcodeLog(sysVcodeLog);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 查询发送消息记录列表
     * /sysVcodeLog/selectSysVcodeLogList
     * { "id":"消息记录",  "username":"手机号码",  "vcode":"动态密码",  "createDate":"获取时间" }
     *
     * @param id         消息记录
     * @param username   手机号码
     * @param vcode      动态密码
     * @param createDate 获取时间
     * @return
     */
    @GetMapping("/selectSysVcodeLogList")
    public Map<String, Object> selectSysVcodeLogList(SysVcodeLog sysVcodeLog) {
        List<SysVcodeLog> sysVcodeLogs = sysVcodeLogService.selectSysVcodeLogList(sysVcodeLog);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sysVcodeLogs", sysVcodeLogs);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }

    /**
     * 查询发送消息记录列表
     * /sysVcodeLog/selectSysVcodeLogCount
     * { "id":"消息记录", "username":"手机号码", "vcode":"动态密码", "createDate":"获取时间"}
     *
     * @param id         消息记录
     * @param username   手机号码
     * @param vcode      动态密码
     * @param createDate 获取时间
     * @return
     */
    @GetMapping("/selectSysVcodeLogCount")
    public Map<String, Object> selectSysVcodeLogCount(SysVcodeLog sysVcodeLog) {
        int count = sysVcodeLogService.selectSysVcodeLogCount(sysVcodeLog);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("count", count);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 查询发送消息记录列表分页
     * /sysVcodeLog/selectSysVcodeLogPage
     * { "id":"消息记录",  "username":"手机号码",  "vcode":"动态密码",  "createDate":"获取时间" ,"pageNum":"页码","pageSize":"条数"}
     *
     * @param pageNum    页码
     * @param pageSize   页数
     * @param id         消息记录
     * @param username   手机号码
     * @param vcode      动态密码
     * @param createDate 获取时间
     * @return
     */
    @GetMapping("/selectSysVcodeLogPage")
    public Map<String, Object> selectSysVcodeLogPage(SysVcodeLog sysVcodeLog, Integer pageNum, Integer pageSize) {
        AssertUtils.notNull(pageNum, "页码不能为空!");
        AssertUtils.notNull(pageSize, "条数不能为空!");
        PageHelper.startPage(pageNum, pageSize);
        List<SysVcodeLog> sysVcodeLogs = sysVcodeLogService.selectSysVcodeLogList(sysVcodeLog);
        PageInfo<SysVcodeLog> pageInfo = new PageInfo<>(sysVcodeLogs);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageInfo", pageInfo);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 导出发送消息记录
     * /sysVcodeLog/exportSysVcodeLogExcel
     * { "id":"消息记录",  "username":"手机号码",  "vcode":"动态密码",  "createDate":"获取时间" }
     *
     * @param id         消息记录
     * @param username   手机号码
     * @param vcode      动态密码
     * @param createDate 获取时间
     * @return
     */
    @GetMapping("/exportSysVcodeLogExcel")
    public void exportSysVcodeLogExcel(HttpServletRequest request, HttpServletResponse response, SysVcodeLog sysVcodeLog) {
        List<SysVcodeLog> sysVcodeLogs = sysVcodeLogService.selectSysVcodeLogList(sysVcodeLog);
        if (CommonUtils.isNotEmpty(sysVcodeLogs)) {
            List<String> titles = new ArrayList<>();
            titles.add(" 序号 ");
            titles.add(" 手机号码 ");
            titles.add(" 动态密码 ");
            titles.add(" 获取时间 ");
            List<List<String>> values = new ArrayList<>();
            int k = 0;
            for (SysVcodeLog entity : sysVcodeLogs) {
                List<String> value = new ArrayList<>();
                value.add((++k) + "");
                value.add(entity.getUsername());
                value.add(entity.getVcode());
                value.add(DateUtils.formatDate(entity.getCreateDate()));
                values.add(value);
            }
            String address = Constants.address + "/wisdom/template/customTemplate.xls";
            String excelName = "发送消息记录.xls";
            Map<String, Object> beans = new HashMap<>();
            beans.put("titles", titles);
            beans.put("values", values);
            beans.put("date", DateUtils.formatDateTime(new Date()));
            JxlsExport.export(request, response, beans, excelName, address);
        }
    }


    /**
     * /sysVcodeLog/importSysVcodeLogExcel  从excel表导入发送消息记录
     * 导入excel文件
     * {"file":"excel文件"}
     *
     * @param file excel文件
     */
    @PostMapping("/importSysVcodeLogExcel")
    public Map<String, Object> importSysVcodeLogExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtils.getResult(ResultInfo.UPLOAD_NOT_EXISTS);
        }
        // 文件名称
        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return ResultUtils.getResult(ResultInfo.UPLOAD_NOT_EXISTS);
        }
        try {
            InputStream inputStream = file.getInputStream();
            //创建工作簿
            Workbook wb = null;
            //判断表格格式
            if (fileName.toLowerCase().endsWith("xls")) {
                wb = new HSSFWorkbook(inputStream);
            } else if (fileName.toLowerCase().endsWith("xlsx")) {
                wb = new XSSFWorkbook(inputStream);
            } else {
                return ResultUtils.getResult(ResultInfo.UPLOAD_TYPE_ERROR);
            }
            List<SysVcodeLog> sysVcodeLogs = new ArrayList<>();
            List<Map<String, String>> resultMap = new ArrayList<>();
            Map<String, String> result = null;
            SysVcodeLog sysVcodeLog = null;
            // 获取工作表的第一个Sheet
            Sheet hssfSheet = wb.getSheetAt(0);
            if (hssfSheet != null) {
                int index = -1;
                for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                        if (ExcelUtils.getValue(hssfRow.getCell(0)).contains("手机号码") &&
                                ExcelUtils.getValue(hssfRow.getCell(1)).contains("动态密码") &&
                                ExcelUtils.getValue(hssfRow.getCell(2)).contains("获取时间")) {
                            index = ++rowNum;
                            break;
                        }
                    }
                }

                if (index == -1) {
                    result = new HashMap<>();
                    result.put("reason", "excel模板不正确");
                    result.put("status", "1");
                    resultMap.add(result);
                    Map<String, Object> map = new HashMap<>();
                    map.put("resultMap", resultMap);
                    return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
                }

                // 循环行Row
                for (int rowNum = index; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                        if (StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(0))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(1))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(2)))) {
                            continue;
                        }
                        sysVcodeLog = new SysVcodeLog();
                        String username = ExcelUtils.getValue(hssfRow.getCell(0));//手机号码
                        if (StringUtils.isBlank(username)) {
                            result = new HashMap<>();
                            result.put("reason", "手机号码不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        sysVcodeLog.setUsername(username);
                        String vcode = ExcelUtils.getValue(hssfRow.getCell(1));//动态密码
                        if (StringUtils.isBlank(vcode)) {
                            result = new HashMap<>();
                            result.put("reason", "动态密码不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        sysVcodeLog.setVcode(vcode);
                        String createDate = ExcelUtils.getValue(hssfRow.getCell(2));//获取时间
                        if (StringUtils.isBlank(createDate)) {
                            result = new HashMap<>();
                            result.put("reason", "获取时间不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        sysVcodeLog.setCreateDate(DateUtils.formatDate(createDate));
                        sysVcodeLogs.add(sysVcodeLog);
                    }
                }
                if (CommonUtils.isNotEmpty(sysVcodeLogs)) {
                    resultMap.addAll(sysVcodeLogService.importSysVcodeLogExcel(sysVcodeLogs));
                }
            }
            inputStream.close();
            Map<String, Object> map = new HashMap<>();
            map.put("resultMap", resultMap);
            return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.getResult(ResultInfo.ERROR);
        }
        return ResultUtils.getResult(ResultInfo.FAILED);
    }
}